package com.suns.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suns.dao.ApplicationDao;
import com.suns.dao.UserDao;
import com.suns.domain.Admin;
import com.suns.domain.Application;
import com.suns.domain.User;
import com.suns.service.ApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ApplcationServiceImpl implements ApplicationService {
    @Autowired
    private ApplicationDao applicationDao;

    @Autowired
    UserDao userDao;

    @Override
    public PageInfo<Application> getPageAPList(int i, int pageSize, String keywords) {
        // 使用 PageHelper 进行分页操作
        PageHelper.startPage(i, pageSize);
        LambdaQueryWrapper<Application> wrapper = new LambdaQueryWrapper<Application>();
        if(!Objects.equals(keywords, "null")){
            String likeKeywords = "%" + keywords.toLowerCase() + "%";
            wrapper.like(Application::getId,likeKeywords)
                    .or().like(Application::getName,likeKeywords)
                    .or().like(Application::getTel,likeKeywords)
                    .or().like(Application::getUsertype,likeKeywords)
                    .or().like(Application::getRemoney,likeKeywords)
                    .or().like(Application::getTime,likeKeywords);
        }
        List<Application> apList = applicationDao.selectList(wrapper);
        return new PageInfo<>(apList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) //开启事务
    public boolean delaps(List<Integer> ids,List<String> tels,List<Integer> mns,Integer sh) {
        //更新application表中的时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String nowStr = formatter.format(now);
        LambdaUpdateWrapper<Application> wp = new LambdaUpdateWrapper<>();
        wp.in(Application::getId, ids)
                .set(Application::getTime,nowStr);
        int rows2=applicationDao.update(null,wp);
        if(rows2!=tels.size()){
            throw new RuntimeException("存在账户时间更新失败,批量审批失败!"); // 抛出异常
        }
        //更新用户表中的余额
        if(sh==1){
            LambdaQueryWrapper<User> wp_ca=new LambdaQueryWrapper<>();
            wp_ca.in(User::getTel,tels).select(User::getMoney);
            List<User> userMoneyList = userDao.selectList(wp_ca);
            List<BigDecimal> oldBalances = new ArrayList<>();
            for (User user : userMoneyList) {
                oldBalances.add(user.getMoney());
            }
            if(oldBalances.size()!= tels.size()){
                throw new RuntimeException("信息数量获取异常,批量审批失败");
            }
            List<BigDecimal> newBalances=new ArrayList<>();
            for(int i=0;i<oldBalances.size();i++){
                if(oldBalances.get(i).compareTo(BigDecimal.valueOf(mns.get(i)))<0){
                    throw new RuntimeException("存在账户申请退款大于余额,批量审批失败!");
                }
                BigDecimal j=BigDecimal.valueOf(mns.get(i));
                newBalances.add(oldBalances.get(i).subtract(j));
            }
            LambdaUpdateWrapper<User> wp_up = new LambdaUpdateWrapper<>();
            for (int i=0;i<newBalances.size();i++){
                wp_up.eq(User::getTel,tels.get(i))
                        .set(User::getMoney,newBalances.get(i));
                if(userDao.update(null,wp_up)==0){
                    throw new RuntimeException("存在账户余额更新失败,批量审批失败!");
                }
            }
        }
        //更新申请状态
        LambdaUpdateWrapper<Application> wp_upAP=new LambdaUpdateWrapper<>();
        String state= sh==1 ? "已通过":"已拒绝";
        for (Integer id : ids) {
            wp_upAP.eq(Application::getId, id)
                    .set(Application::getState, state);
            if (applicationDao.update(null, wp_upAP) == 0) {
                throw new RuntimeException("存在申请状态更新失败,批量审批失败!");
            }
        }
        LambdaQueryWrapper<Application> wrapper = new LambdaQueryWrapper<Application>();
        wrapper.in(Application::getId, ids);
        int rows =applicationDao.delete(wrapper);
        if(rows!=tels.size()){
            throw new RuntimeException("存在账户申请状态更新失败,批量审批失败!"); // 抛出异常
        }
        return true;
    }

    @Override
    public BigDecimal get_Outcome(String usertype, String day, String month) {
        LambdaQueryWrapper<Application> wrapper = new LambdaQueryWrapper<Application>();
        wrapper.eq(Application::getUsertype,usertype)
                .eq(Application::getDeleted,1);
        if(!Objects.equals(day, "null")){
            wrapper.and(w->w.apply("DATE_FORMAT(`time`, '%Y-%m-%d') = DATE_FORMAT({0}, '%Y-%m-%d')", day));
            return applicationDao.selectAps(wrapper)
                    .stream().map(Application::getRemoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }else {
            String likeMonth = "%" + month.toLowerCase() + "%";
            wrapper.like(Application::getTime,likeMonth);
            return applicationDao.selectAps(wrapper)
                    .stream().map(Application::getRemoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
    }

    @Override
    public PageInfo<Application> getPageaps(int i, int pageSize, String keywords) {
        // 使用 PageHelper 进行分页操作
        PageHelper.startPage(i, pageSize);
        LambdaQueryWrapper<Application> wrapper = new LambdaQueryWrapper<Application>();
        wrapper.eq(Application::getDeleted,1);
        if(!Objects.equals(keywords, "null")){
            String likeKeywords = "%" + keywords.toLowerCase() + "%";
            wrapper.and(w->w.like(Application::getId,likeKeywords)
                    .or().like(Application::getName,likeKeywords)
                    .or().like(Application::getTel,likeKeywords)
                    .or().like(Application::getUsertype,likeKeywords)
                    .or().like(Application::getRemoney,likeKeywords)
                    .or().like(Application::getTime,likeKeywords)
                    .or().like(Application::getState,likeKeywords));
        }
        List<Application> apList = applicationDao.selectAps(wrapper);
        return new PageInfo<>(apList);
    }
    //在application表中添入新数据
    @Override
    public boolean userreturn(String name, String tel, BigDecimal remoney, String time, String usertype) {
        Application application = new Application();
        application.setName(name);
        application.setTel(tel);
        application.setRemoney(remoney);
        application.setTime(time);
        application.setUsertype(usertype);
        application.setState(null);
        return applicationDao.insert(application)==1;
    }

    @Override
    public String getUserDel(String tel) {
        LambdaQueryWrapper<Application>wp=new LambdaQueryWrapper<>();
        wp.eq(Application::getTel,tel);
        Application application=applicationDao.selectOne(wp);
        if(application!=null){
            LambdaQueryWrapper<Application> wrapper = new LambdaQueryWrapper<Application>();
            wrapper.eq(Application::getTel,tel)
                    .eq(Application::getDeleted,1)
                    .orderByDesc(Application::getId).last("limit 1");
            List<Application> ap= applicationDao.selectAps(wrapper);
            if(!ap.isEmpty()){
                return ap.get(0).getState();
            }else {
                return "待审批";
            }
        }
        return "未提交申请";
    }
}
